package com.prime;

import java.util.Map;
import java.util.concurrent.*;

public class RightPrimeChecker implements CanCheckIfPrime {

    private static ConcurrentHashMap<Integer, Future<Boolean>> primeCache = new ConcurrentHashMap<>();

    @Override
    public final boolean isPrime(int number) {
        Future<Boolean> f = primeCache.get(number);
        if (f == null) {
            Callable<Boolean> eval = () -> compute(number);
            FutureTask<Boolean> ft = new FutureTask<>(eval);
            f = primeCache.putIfAbsent(number, ft);
            if (f == null) {
                f = ft;
                ft.run();
            }
        }
        try {
            return f.get();
        } catch (CancellationException | InterruptedException | ExecutionException e) {
            primeCache.remove(number, f);
            e.printStackTrace();
        }
        return false;
    }

    private Boolean compute(int number) {
        int sqrt = (int) Math.sqrt(number) + 1;
        for (int i = 2; i < sqrt; i++) {
            if (number % i == 0) {
                return false;
            }
        }
        return true;
    }

    public static void main(String[] args) throws ExecutionException, InterruptedException {
        int numThreads = Runtime.getRuntime().availableProcessors() - 1;
        System.out.println("Starting " + numThreads + " threads to calculate.");
        ExecutorService executor = Executors.newFixedThreadPool(numThreads);
        Integer counter = 0;
        for (int i = 0; i < numThreads; i++) {
            Runnable worker = () -> {
                RightPrimeChecker checker = new RightPrimeChecker();
                for (int j = Integer.MAX_VALUE; j >= 2; j--) {
                    checker.isPrime(j);
                }
            };
            executor.execute(worker);
        }
        executor.shutdown();
        while (!executor.isTerminated()) {}
        System.out.println("Finished all threads");
        for (Map.Entry<Integer, Future<Boolean>> entry: primeCache.entrySet()){
            if (entry.getValue().get()){
                counter++;
            }
        }
        System.out.println("Prime numbers count is: " + counter);
    }
}